<?php

namespace App\Services\MiniprogramToGame;

use App\Models\Log\LogPokemonVote;
use App\Models\PokemonVoteData;
use App\Services\ServiceBase;

class PokemonVoteService extends ServiceBase
{
    public function getOrCreate($appid)
    {
        $class = PokemonVoteData::where('appid', $appid)->first();
        if (!$class) {
            $class = new PokemonVoteData;
            $class->create_time = time();
            $class->appid = $appid;
            $class->vote_list = '';
            $class->save();
        }

        return $class;
    }

    public function userVote($appid, $item_id)
    {
        $class = $this->getOrCreate($appid);
        $vote_list = json_decode($class->vote_list, true);
        if (empty($vote_list)) {
            for ($i=1; $i <= 20; $i++) {
                $vote_list[$i] = 0;
            }
        }
        $num = $vote_list[$item_id] ?? 0;
        $vote_list[$item_id] = $num + 1;
        $class->vote_list = json_encode($vote_list);
        $class->save();

        return true;
    }

    public function getInfo($appid, $openid)
    {
        $data = [
            'vote_list' => [],
            'is_vote' => 0,
            'vote_time_id' => 0,
        ];
        $class = $this->getOrCreate($appid);
        $list = json_decode($class->vote_list, true) ?? [];
        foreach ($list as $id => $value) {
            $data['vote_list'][] = [
                'item_id' => $id,
                'num' => $value
            ];
        }
        $log = LogPokemonVote::where('openid', $openid)->where('appid', $appid)->first();
        if ($log) {
            $data['is_vote'] = 1;
            $data['vote_time_id'] = $log->item_id;
        }

        return $data;
    }
}
